<template>
  <div class="goodadd">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <el-steps
        finish-status="success"
        space="200px"
        :align-center="true"
        :active="active"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-tabs
        :tab-position="tabPosition"
        style="height: 200px;"
        @tab-click="index($event)"
        stretch
        :before-leave="beforeLeaveTab"
      >
        <el-tab-pane label="基本信息">
          <el-form ref="goodsform" :rules="rules" :model="goodsform">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="goodsform.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="goodsform.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="goodsform.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="goodsform.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <div class="block">
                <el-cascader
                  v-model="goodsform.goods_cat"
                  :options="goodsform.CategoriesList"
                  :props="{
                    expandTrigger: 'hover',
                    value: 'cat_id',
                    label: 'cat_name',
                  }"
                  @change="getAttributesList"
                ></el-cascader>
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="商品参数">
          <el-checkbox-group
            v-model="checkList"
            @change="handleCheckedCitiesChange"
          >
            <el-row v-for="(city, i) in manyAttributes" :key="i">
              <span
                class="spanBox"
                style="font-size: 16px; margin-right: 20px;"
                >{{ city.attr_name }}</span
              >
              <el-checkbox
                v-for="(v, i) in city.attr_vals"
                :label="v"
                :key="i"
                border
                >{{ v }}</el-checkbox
              >
            </el-row>
          </el-checkbox-group>
        </el-tab-pane>
        <el-tab-pane label="商品属性">
          <el-checkbox-group
            v-model="checkList2"
            @change="handleCheckedCitiesChange"
          >
            <el-row v-for="(city, i) in onlyAttributes" :key="i">
              <span
                class="spanBox"
                style="font-size: 16px; margin-right: 20px;"
                >{{ city.attr_name }}</span
              >
              <!-- {{ city.attr_vals.join(',') }} -->
              <el-input v-model="onlyAttributes[i].attr_vals"></el-input>
              <!-- <el-checkbox
                v-for="(v, i) in city.attr_vals"
                :label="v"
                :key="i"
                border
                >{{ v }}</el-checkbox
              > -->
            </el-row>
          </el-checkbox-group>
        </el-tab-pane>
        <el-tab-pane label="商品图片">
          <el-upload
            action="http://127.0.0.1:8888/api/private/v1/upload"
            :headers="headersObj"
            list-type="picture-card"
            :on-success="uploadImg"
            :file-list="fileList"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file, fileList)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-tab-pane>
        <el-tab-pane label="商品内容">
          <!-- 富文本编辑器组件 -->
          <quill-editor v-model="goodsform.goods_introduce"> </quill-editor>
          <el-button type="primary" class="addbtn" @click="postGoods"
            >添加商品</el-button
          >
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'GoodAdd',
  data() {
    return {
      tabPosition: 'left',
      active: 0,
      // 选中的静态参数
      checkList: [],
      // 选中的动态参数
      checkList2: [],
      // 静态属性
      onlyAttributes: [],
      // 动态参数
      manyAttributes: [],
      goodsform: {
        CategoriesList: [],
        goods_name: '',
        goods_weight: 0,
        goods_number: 0,
        goods_cat: '',
        goods_price: 0,
        goods_introduce: '',
        pics: [],
      },
      rules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { validator: this.rulesNumber1, trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          { validator: this.rulesNumber2, trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { validator: this.rulesNumber3, trigger: 'blur' },
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'change' },
        ],
      },
      // 图片上传的参数
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      fileList: [],
      headersObj: {
        Authorization: window.localStorage.getItem('token'),
      },
    };
  },
  methods: {
    // 处理选中的动态参数给一个数组
    dtcs(arr) {
      this.checkList.forEach((v) => {
        this.manyAttributes.forEach((v1) => {
          v1.attr_vals.forEach((v2) => {
            if (v2 === v) {
              let flag = false;
              arr.forEach((v3) => {
                if (v3.attr_id === v1.attr_id) {
                  v3.attr_value += ',' + v;
                  flag = true;
                }
              });
              if (flag) {
                return false;
              }
              arr.push({
                attr_id: v1.attr_id,
                attr_value: v,
              });
            }
          });
        });
      });
      return arr;
    },
    // 添加商品
    postGoods() {
      this.active = 5;
      const arr1 = [];
      this.dtcs(arr1);
      const arr2 = this.onlyAttributes.map((v) => {
        return { attr_id: v.attr_id, attr_vals: v.attr_vals };
      });

      this.__apis.goods
        .postGoods({
          goods_name: this.goodsform.goods_name,
          goods_weight: this.goodsform.goods_weight,
          goods_number: this.goodsform.goods_number,
          goods_cat: this.goodsform.goods_cat.join(','),
          goods_price: this.goodsform.goods_price,
          goods_introduce: this.goodsform.goods_introduce,
          pics: this.goodsform.pics,
          attrs: [...arr1, ...arr2],
        })
        .then((res) => {
          // console.log(res);
          if (res.data.meta.status === 201) {
            this.$message.success('添加商品成功');
            this.active = 6;
            this.$router.push('/goods');
          } else {
            this.$message.error(res.data.meta.msg);
          }
        });
    },
    // 上传文件成功后调用的钩子函数
    uploadImg(file) {
      this.fileList.push(file.data);
      this.$message.success('上传成功');
      this.goodsform.pics.push({ pic: file.data.tmp_path });
    },
    // 图片删除
    handleRemove(file, fileList) {
      fileList.forEach((v, i) => {
        if (v.uid === file.uid) {
          fileList.splice(i, 1);
        }
      });
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 参数选中项
    handleCheckedCitiesChange(value) {
      // console.log(value);
    },
    // 分类选择后获取参数列表
    getAttributesList() {
      this.getAttributes('only');
      this.getAttributes('many');
    },
    // 获取参数列表
    getAttributes(sel) {
      // console.log(sel);
      this.__apis.attributes
        .getAttributes({
          id: this.goodsform.goods_cat[2],
          sel,
        })
        .then((res) => {
          if (sel === 'only') {
            if (res.data.meta.status === 200) {
              this.onlyAttributes = res.data.data;
              // this.onlyAttributes.forEach((v) => {
              //   v.attr_vals = v.attr_vals.split(',');
              //   v.attr_vals.forEach((v2, i) => {
              //     if (v2 === '') {
              //       v.attr_vals.splice(i, 1);
              //     }
              //   });
              // });
            } else {
              this.$message.error(res.data.meta.msg);
            }
          } else if (sel === 'many') {
            if (res.data.meta.status === 200) {
              this.manyAttributes = res.data.data;
              this.manyAttributes.forEach((v) => {
                v.attr_vals = v.attr_vals.split(',');
                v.attr_vals.forEach((v2, i) => {
                  if (v2 === '') {
                    v.attr_vals.splice(i, 1);
                  }
                });
              });
            } else {
              this.$message.error(res.data.meta.msg);
            }
          }
        });
    },
    // 验证表单跳转
    beforeLeaveTab(activeName) {
      if (activeName !== '0') {
        return this.$refs.goodsform.validate();
      }
    },
    // 自定义表单校检规则1
    rulesNumber1(rule, value, callback) {
      if (
        (!/^([0-9]{1,})$/.test(value) &&
          !/^([0-9]{1,}[.][0-9]*)$/.test(value)) ||
        +value <= 0
      ) {
        return callback(new Error('商品价格必须是大于0的整数或小数'));
      }
      callback();
    },
    // 自定义表单校检规则2
    rulesNumber2(rule, value, callback) {
      if (
        (!/^([0-9]{1,})$/.test(value) &&
          !/^([0-9]{1,}[.][0-9]*)$/.test(value)) ||
        +value <= 0
      ) {
        return callback(new Error('商品价重量必须是大于0的整数或小数'));
      }
      callback();
    },
    // 自定义表单校检规则3
    rulesNumber3(rule, value, callback) {
      if (typeof value !== 'number' || value <= 0) {
        return callback(new Error('商品数量必须是大于0的整数'));
      }
      callback();
    },

    handleChange(value) {
      // console.log(value);
    },
    // 标签页控制步骤条
    index(e) {
      // if (e.index !== '0' && this.goodsform.goods_cat === '') {
      //   return false;
      // }
      // this.active = +e.index;

      this.$refs.goodsform
        .validate()
        .then(() => {
          this.active = +e.index;
        })
        .catch(() => {
          return false;
        });
    },
    // 获取分类数据
    getCategoriesList() {
      this.__apis.goods
        .getCategoriesList({ type: '', pagenum: '', pagesize: '' })
        .then((res) => {
          if (res.data.meta.status === 200) {
            this.goodsform.CategoriesList = res.data.data;
            this.goodsform.CategoriesList.forEach((v) => {
              if (!v.children) {
                v.disabled = true;
              }
              v.children.forEach((v) => {
                if (!v.children) {
                  v.disabled = true;
                }
              });
            });
          }
          // console.log(res);
        });
    },
  },
  created() {
    this.getCategoriesList();
  },
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  font-size: 12px;
}
.el-card {
  margin-top: 20px;
  min-width: 1120px;
  .el-alert {
    margin-bottom: 20px;
  }
  .el-steps {
    margin-bottom: 20px;
  }
  .el-step__title.is-success,
  .el-step__title.is-process {
    font-size: 12px !important;
  }
  .el-step__title {
    font-size: 12px !important;
  }
  .el-tabs.el-tabs--left {
    height: 100% !important;
    margin-top: 10px;
  }
  .el-cascader {
    width: 100%;
  }
  .block /deep/ .el-input {
    width: 200px;
  }
  /deep/ .el-step__title {
    font-size: 12px;
  }
  .quill-editor {
    height: 367px;
  }
  /deep/ .ql-editor,
  /deep/ .ql-container {
    height: 300px;
  }
  .addbtn {
    margin-top: 15px;
  }
}
</style>
